package com.nd.qa.shareplate.script.robotium;


import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.nd.qa.shareplate.common.PropertiesManager;
import com.nd.qa.shareplate.util.FileUtil;

public class CompileApk {
	
	Logger log = LoggerFactory.getLogger(CompileApk.class);
	
	FileUtil fileUtil = new FileUtil();
	String scriptRootPath = null;
	String packageName = null;
	String classPath = null;
	String binPath = null;
	String genPath = null;
	String libsPath = null;
	String srcPath = null;
	String resPath = null;
	String manifastXmlPath = null;

	public CompileApk(String scriptRootPath, String packageName) {
		this.scriptRootPath = scriptRootPath;
		this.packageName = packageName;
		this.binPath = this.scriptRootPath + "/bin";
		this.genPath = this.scriptRootPath + "/gen";
		this.libsPath = this.scriptRootPath + "/libs";
		this.srcPath = this.scriptRootPath + "/src";
		this.resPath = this.scriptRootPath + "/res";
		this.manifastXmlPath = this.scriptRootPath + "/AndroidManifest.xml";
		this.classPath = packageName.replaceAll("\\.", "/");
	}

	// 初始化,创建gen bin目录
	private void init() {
		fileUtil.deleteDir(new File(binPath));
		fileUtil.deleteDir(new File(genPath));
		fileUtil.createDir(binPath);
		fileUtil.createDir(genPath);
	}

	public String compileApk() {
		String result = "";
		// 初始化
		init();
		// 生成R.JAVA文件
		result = createR();
		if (result.contains("错误")||result.contains("Exception")) {
			return result;
		}
		// 编译java文件
		result = compileJava();
		if (result.contains("错误")||result.contains("Exception")) {
			return result;
		}
		// 生成dex文件，添加相关jar文件
		result = createDex();
		if (result.contains("错误")||result.contains("Exception")) {
			return result;
		}
		// 打包资源文件
		result = createResources();
		if (result.contains("错误")||result.contains("Exception")) {
			return result;
		}
		// 生成apk
		result = createApk();
		if (result.contains("错误")||result.contains("Exception")) {
			return result;
		}
		// 对apk进行签名,先判断使用哪个签名文件签名
		/*findRSA(apkLocalPath);
		unconpressAPK(apkLocalPath);
		String SHAStr = getFingerPrints();
		if (SHAStr!=null&&!"".equals(SHAStr)) {
			String key = SHAStr.split("SHA256:")[1].trim().replaceAll("/n", "");
			//result = signApk(key);
		}*/
		result = signApk();
		if (result.contains("错误")||result.contains("Exception")) {
			return result;
		}
		
		return result;
	}
	//查找apk里的rsa文件
    private String findRSA(String apkLocalPath){
    	String cmd = String
				.format("jar tf %s |findstr RSA",apkLocalPath);//jar tf HelloWorld.apk |grep RSA (for linux)
    	System.out.println("findRSA==="+cmd);
		return runCommond(cmd);
    }
    //从apk中解压rsa文件
    private String unconpressAPK(String apkLocalPath){
    	String cmd = String
				.format("jar xf %s META-INF/CERT.RSA",apkLocalPath);//jar tf HelloWorld.apk |grep RSA (for linux)
    	System.out.println("unconpressAPK==="+cmd);
		return runCommond(cmd);
    }
    //获取签名的fingerprints
    private String getFingerPrints(){
    	String cmd = String
				.format("cmd /c keytool -printcert -file META-INF/CERT.RSA | findstr SHA256:");//jar tf HelloWorld.apk |grep RSA (for linux)
    	System.out.println("getFingerPrints==="+cmd);
		return runCommond(cmd);
    }
	private String runCommond(String cmd) {
		Process p = null;
		StringBuilder sb=new StringBuilder();
		try {
			p = Runtime.getRuntime().exec(cmd);
			BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream(), "GBK"));
			BufferedReader inputBuffer = new BufferedReader(new InputStreamReader(p.getInputStream(), "GBK")); 
            String line;  
            String inline;  
            while((line=br.readLine())!=null){  
                sb.append(line);  
                sb.append("/n");  
            }
            System.out.println("first======="+sb.toString());
            while((inline=inputBuffer.readLine())!=null){  
                sb.append(inline);
                sb.append("/n");  
            }
            System.out.println("second======="+sb.toString());
            if (sb!=null) {
            	if (sb.toString().contains("错误")||sb.toString().contains("Exception")) {
                	log.error("错误结果:"+sb.toString());
                    System.out.println("错误结果:"+sb.toString());
    			}
			}
            br.close();
            inputBuffer.close();
            p.destroy();  
			p.waitFor();
		} catch (Exception e) {
			log.error("runCommond==="+e);
			e.printStackTrace();
		}
		return sb.toString();
	}

	private String signApk() {
		String cmd = "";
		if ("com.nd.app.factory.imapp0.test".equals(packageName)) {
			cmd = String
					.format("jarsigner -digestalg SHA1 -sigalg MD5withRSA -keystore %s -storepass android -keypass android %s %s",
							PropertiesManager.debugKeyStorePath, binPath
									+ "/test.apk",PropertiesManager.debugAlias);
		}else {
			cmd = String
					.format("jarsigner -digestalg SHA1 -sigalg MD5withRSA -keystore %s -storepass android -keypass android %s %s",
							PropertiesManager.predebugKeyStorePath, binPath
									+ "/test.apk",PropertiesManager.predebugAlias);
		}
		
		
		System.out.println("signApk==="+cmd);
		return runCommond(cmd);
	}

	private String createApk() {
		//linux需要把cmd /c 
		String cmd = String.format(
				"cmd /c apkbuilder %s -v -u -z %s -f %s -rf %s -nf %s -rj %s ",
				binPath + "/test.apk", binPath + "/resources.ap_", binPath
						+ "/classes.dex", srcPath, libsPath, libsPath);
		System.out.println("createApk==="+cmd);
		return runCommond(cmd);
	}

	private String createResources() {
		String cmd = String.format("aapt package -f -S %s -I %s -M %s -F %s",
				resPath, PropertiesManager.androidJarPath, manifastXmlPath,
				binPath + "/resources.ap_");
		System.out.println("createResources==="+cmd);
		return runCommond(cmd);
	}

	private String createDex() {
		//linux需要把cmd /c 删除 
		String cmd = String.format("cmd /c dx --dex --output=%s %s %s", binPath
				+ "/classes.dex", binPath, libsPath + "/*.jar");
		System.out.println("createDex==="+cmd);
		return runCommond(cmd);
	}

	private String compileJava() {

		String cmd = String
				.format("javac -encoding UTF-8 -source %s -target %s -bootclasspath %s -d %s %s/*.java  %s/*.java %s/*.java  -classpath %s",
						PropertiesManager.javaTarget,
						PropertiesManager.javaTarget,
						PropertiesManager.androidJarPath, binPath, srcPath+"/com/nd/qa/test/common",srcPath
								+ "/" + classPath, genPath + "/" + classPath,
						libsPath + "/robotium.jar");
		System.out.println("compileJava==="+cmd);
		return runCommond(cmd);
	}
	
	private String createR() {
		String cmd = String.format("aapt p -f -m -J %s -S %s -I %s -M %s",
				genPath, resPath, PropertiesManager.androidJarPath,
				manifastXmlPath);
		System.out.println("createR==="+cmd);
		return runCommond(cmd);
	}
}
